package com.inspur.edp.ide.config.webapi.entity;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.ResolvableDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ValueNode;
import io.iec.edp.caf.boot.context.CAFContext;

import java.io.IOException;

public class PanelDescriptionDeserializer extends JsonDeserializer<PanelDescription> implements ResolvableDeserializer {
    private final static String LANGUAGE_DEFAULT = "zh-CHS";
    private final static String KEY_CONNECTOR = "_";
    private final static String KEY_TITLE = "title";

    private JsonDeserializer<?> defaultDeserializer;

    public PanelDescriptionDeserializer(JsonDeserializer<?> defaultDeserializer) {
        super();
        this.defaultDeserializer = defaultDeserializer;
    }

    public static SimpleModule createModule() {
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
                if (beanDesc.getBeanClass() == PanelDescription.class) {
                    return new PanelDescriptionDeserializer(deserializer);
                }
                return deserializer;
            }
        });
        return module;
    }

    @Override
    public PanelDescription deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        String language = CAFContext.current.getLanguage();
        String postfix = LANGUAGE_DEFAULT.equals(language) ? "" : KEY_CONNECTOR + language;

        PanelDescription panelDescription;
        TreeNode treeNode = jsonParser.readValueAsTree();
        try (JsonParser jp = jsonParser.getCodec().treeAsTokens(treeNode)) {
            if (jp.currentToken() == null) {
                jp.nextToken();
            }
            panelDescription = (PanelDescription) defaultDeserializer.deserialize(jp, deserializationContext);
            TreeNode nameNode = treeNode.get(KEY_TITLE + postfix);
            if (nameNode != null && nameNode.isValueNode()) {
                panelDescription.setTitle(((ValueNode) nameNode).asText(""));
            }
        }

        return panelDescription;
    }

    @Override
    public void resolve(DeserializationContext deserializationContext) throws JsonMappingException {
        ((ResolvableDeserializer) defaultDeserializer).resolve(deserializationContext);
    }
}
